@echo off
REM Vault MySQL高并发服务 - Windows部署脚本
REM 用于在Windows环境下自动化部署和管理应用服务

setlocal enabledelayedexpansion

REM 配置变量
set APP_NAME=vault-mysql-service
set DOCKER_IMAGE=vault-mysql-service:latest
set COMPOSE_FILE=docker-compose.yml
set ENV_FILE=.env
set BACKUP_DIR=.\backups
set LOG_DIR=.\logs

REM 颜色代码（Windows 10+）
set RED=[91m
set GREEN=[92m
set YELLOW=[93m
set BLUE=[94m
set NC=[0m

REM 函数：打印带颜色的消息
:print_message
echo %~2[%date% %time%] %~3%NC%
goto :eof

:print_info
call :print_message "%BLUE%" "%~1"
goto :eof

:print_success
call :print_message "%GREEN%" "%~1"
goto :eof

:print_warning
call :print_message "%YELLOW%" "%~1"
goto :eof

:print_error
call :print_message "%RED%" "%~1"
goto :eof

REM 函数：检查依赖
:check_dependencies
call :print_info "检查系统依赖..."

REM 检查Docker
docker --version >nul 2>&1
if errorlevel 1 (
    call :print_error "Docker未安装，请先安装Docker Desktop"
    exit /b 1
)

REM 检查Docker Compose
docker-compose --version >nul 2>&1
if errorlevel 1 (
    call :print_error "Docker Compose未安装，请先安装Docker Compose"
    exit /b 1
)

REM 检查Maven（如果需要本地构建）
if "%~1"=="build" (
    mvn --version >nul 2>&1
    if errorlevel 1 (
        call :print_error "Maven未安装，请先安装Maven或使用Docker构建"
        exit /b 1
    )
)

call :print_success "依赖检查完成"
goto :eof

REM 函数：创建必要的目录
:create_directories
call :print_info "创建必要的目录..."

if not exist "%BACKUP_DIR%" mkdir "%BACKUP_DIR%"
if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"
if not exist "vault-config" mkdir "vault-config"
if not exist "mysql-config" mkdir "mysql-config"
if not exist "mysql-init" mkdir "mysql-init"
if not exist "nginx" mkdir "nginx"
if not exist "monitoring" mkdir "monitoring"

call :print_success "目录创建完成"
goto :eof

REM 函数：生成环境配置文件
:generate_env_file
call :print_info "生成环境配置文件..."

if not exist "%ENV_FILE%" (
    (
        echo # Vault MySQL服务环境配置
        echo.
        echo # 应用配置
        echo SPRING_PROFILES_ACTIVE=docker
        echo SERVER_PORT=8080
        echo.
        echo # Vault配置
        echo VAULT_URL=http://vault:8200
        echo VAULT_TOKEN=myroot
        echo.
        echo # 数据库配置
        echo MYSQL_ROOT_PASSWORD=rootpassword
        echo MYSQL_DATABASE=testdb
        echo MYSQL_USER=testuser
        echo MYSQL_PASSWORD=testpassword
        echo.
        echo # Redis配置
        echo REDIS_PASSWORD=redispassword
        echo.
        echo # 监控配置
        echo GRAFANA_ADMIN_PASSWORD=admin
        echo.
        echo # 应用特定配置
        echo APP_INIT_DATA_ON_STARTUP=true
        echo APP_MAX_CONCURRENT_TESTS=10
        echo APP_DEFAULT_TEST_DURATION=300
        echo.
        echo # 日志级别
        echo LOGGING_LEVEL_ROOT=INFO
        echo LOGGING_LEVEL_COM_EXAMPLE_VAULTMYSQL=DEBUG
    ) > "%ENV_FILE%"
    call :print_success "环境配置文件已生成: %ENV_FILE%"
) else (
    call :print_warning "环境配置文件已存在: %ENV_FILE%"
)
goto :eof

REM 函数：生成MySQL配置文件
:generate_mysql_config
call :print_info "生成MySQL配置文件..."

REM 主数据库配置
(
    echo [mysqld]
    echo server-id=1
    echo log-bin=mysql-bin
    echo binlog-format=ROW
    echo max_connections=1000
    echo innodb_buffer_pool_size=256M
    echo innodb_log_file_size=64M
    echo innodb_flush_log_at_trx_commit=2
    echo sync_binlog=1
) > "mysql-config\primary.cnf"

REM 从数据库配置
(
    echo [mysqld]
    echo server-id=2
    echo relay-log=mysql-relay-bin
    echo log-slave-updates=1
    echo read_only=1
    echo max_connections=1000
    echo innodb_buffer_pool_size=256M
    echo innodb_log_file_size=64M
) > "mysql-config\replica.cnf"

call :print_success "MySQL配置文件已生成"
goto :eof

REM 函数：生成初始化SQL脚本
:generate_init_sql
call :print_info "生成数据库初始化脚本..."

(
    echo -- 创建测试数据库和用户
    echo CREATE DATABASE IF NOT EXISTS testdb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    echo CREATE USER IF NOT EXISTS 'testuser'@'%%' IDENTIFIED BY 'testpassword';
    echo GRANT ALL PRIVILEGES ON testdb.* TO 'testuser'@'%%';
    echo FLUSH PRIVILEGES;
    echo.
    echo -- 创建性能测试表
    echo USE testdb;
    echo.
    echo CREATE TABLE IF NOT EXISTS performance_test (
    echo     id BIGINT AUTO_INCREMENT PRIMARY KEY,
    echo     test_name VARCHAR(255^) NOT NULL,
    echo     test_data TEXT,
    echo     created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    echo     updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    echo     INDEX idx_test_name (test_name^),
    echo     INDEX idx_created_at (created_at^)
    echo ^) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    echo.
    echo -- 插入测试数据
    echo INSERT INTO performance_test (test_name, test_data^) VALUES
    echo ('test1', 'Sample test data 1'^),
    echo ('test2', 'Sample test data 2'^),
    echo ('test3', 'Sample test data 3'^);
) > "mysql-init\01-init.sql"

call :print_success "数据库初始化脚本已生成"
goto :eof

REM 函数：构建应用
:build_app
call :print_info "构建应用..."

if "%~1"=="local" (
    call :print_info "使用Maven进行本地构建..."
    mvn clean package -DskipTests
    if errorlevel 1 (
        call :print_error "Maven构建失败"
        exit /b 1
    )
    call :print_success "Maven构建完成"
)

REM Docker构建
call :print_info "构建Docker镜像..."
docker build -t %DOCKER_IMAGE% .
if errorlevel 1 (
    call :print_error "Docker镜像构建失败"
    exit /b 1
)
call :print_success "Docker镜像构建完成"
goto :eof

REM 函数：启动服务
:start_services
call :print_info "启动服务..."

REM 检查是否已有运行的容器
docker-compose ps | findstr "Up" >nul 2>&1
if not errorlevel 1 (
    call :print_warning "检测到运行中的容器，将先停止现有服务"
    docker-compose down
)

REM 启动服务
docker-compose up -d
if errorlevel 1 (
    call :print_error "服务启动失败"
    exit /b 1
)

call :print_success "服务启动完成"

REM 等待服务就绪
call :print_info "等待服务就绪..."
timeout /t 30 /nobreak >nul

REM 检查服务状态
call :check_services_health
goto :eof

REM 函数：停止服务
:stop_services
call :print_info "停止服务..."
docker-compose down
call :print_success "服务已停止"
goto :eof

REM 函数：重启服务
:restart_services
call :print_info "重启服务..."
call :stop_services
call :start_services
goto :eof

REM 函数：检查服务健康状态
:check_services_health
call :print_info "检查服务健康状态..."

set all_healthy=true

REM 检查应用服务
docker ps --filter "name=vault-mysql-app" --filter "status=running" | findstr "vault-mysql-app" >nul 2>&1
if not errorlevel 1 (
    call :print_success "✓ vault-mysql-app 运行正常"
) else (
    call :print_error "✗ vault-mysql-app 运行异常"
    set all_healthy=false
)

REM 检查Vault服务
docker ps --filter "name=vault-server" --filter "status=running" | findstr "vault-server" >nul 2>&1
if not errorlevel 1 (
    call :print_success "✓ vault-server 运行正常"
) else (
    call :print_error "✗ vault-server 运行异常"
    set all_healthy=false
)

REM 检查MySQL服务
docker ps --filter "name=mysql-primary" --filter "status=running" | findstr "mysql-primary" >nul 2>&1
if not errorlevel 1 (
    call :print_success "✓ mysql-primary 运行正常"
) else (
    call :print_error "✗ mysql-primary 运行异常"
    set all_healthy=false
)

if "%all_healthy%"=="true" (
    call :print_success "所有核心服务运行正常"
    call :print_info "应用访问地址: http://localhost:8080"
    call :print_info "Vault访问地址: http://localhost:8200"
    call :print_info "Grafana访问地址: http://localhost:3000 (admin/admin)"
) else (
    call :print_error "部分服务运行异常，请检查日志"
)
goto :eof

REM 函数：查看日志
:view_logs
set service=%~1
if "%service%"=="" (
    call :print_info "查看所有服务日志..."
    docker-compose logs -f
) else (
    call :print_info "查看 %service% 服务日志..."
    docker-compose logs -f %service%
)
goto :eof

REM 函数：备份数据
:backup_data
call :print_info "备份数据..."

for /f "tokens=1-4 delims=/ " %%a in ('date /t') do set backup_date=%%c%%a%%b
for /f "tokens=1-2 delims=: " %%a in ('time /t') do set backup_time=%%a%%b
set backup_file=%BACKUP_DIR%\backup-%backup_date%-%backup_time%.tar.gz

REM 创建备份
docker run --rm -v vault-mysql-service_mysql-primary-data:/data -v %cd%\%BACKUP_DIR%:/backup alpine tar czf /backup/backup-%backup_date%-%backup_time%.tar.gz -C /data .

if errorlevel 1 (
    call :print_error "数据备份失败"
    exit /b 1
)

call :print_success "数据备份完成: %backup_file%"
goto :eof

REM 函数：清理资源
:cleanup
call :print_warning "清理所有资源（包括数据卷），确认继续？(y/N)"
set /p confirm="请输入选择: "
if /i not "%confirm%"=="y" (
    call :print_info "操作已取消"
    exit /b 0
)

call :print_info "清理资源..."

REM 停止并删除容器、网络、数据卷
docker-compose down -v --remove-orphans

REM 删除镜像
docker images | findstr "%DOCKER_IMAGE%" >nul 2>&1
if not errorlevel 1 (
    docker rmi %DOCKER_IMAGE%
)

call :print_success "资源清理完成"
goto :eof

REM 函数：显示帮助信息
:show_help
echo Vault MySQL高并发服务 - Windows部署脚本
echo.
echo 用法: %~nx0 [命令] [选项]
echo.
echo 命令:
echo   init                初始化项目（创建配置文件和目录）
echo   build [local]       构建应用（可选local进行本地Maven构建）
echo   start               启动所有服务
echo   stop                停止所有服务
echo   restart             重启所有服务
echo   status              检查服务状态
echo   logs [service]      查看日志（可指定服务名）
echo   backup              备份数据
echo   cleanup             清理所有资源
echo   help                显示帮助信息
echo.
echo 示例:
echo   %~nx0 init          # 初始化项目
echo   %~nx0 build         # 构建应用
echo   %~nx0 start         # 启动服务
echo   %~nx0 logs app      # 查看应用日志
echo   %~nx0 backup        # 备份数据
echo.
goto :eof

REM 主函数
:main
set command=%~1
set option=%~2

if "%command%"=="init" (
    call :check_dependencies
    call :create_directories
    call :generate_env_file
    call :generate_mysql_config
    call :generate_init_sql
    call :print_success "项目初始化完成"
) else if "%command%"=="build" (
    call :check_dependencies "build"
    call :build_app %option%
) else if "%command%"=="start" (
    call :check_dependencies
    call :start_services
) else if "%command%"=="stop" (
    call :stop_services
) else if "%command%"=="restart" (
    call :restart_services
) else if "%command%"=="status" (
    call :check_services_health
) else if "%command%"=="logs" (
    call :view_logs %option%
) else if "%command%"=="backup" (
    call :backup_data
) else if "%command%"=="cleanup" (
    call :cleanup
) else if "%command%"=="help" (
    call :show_help
) else if "%command%"=="--help" (
    call :show_help
) else if "%command%"=="-h" (
    call :show_help
) else if "%command%"=="" (
    call :print_error "请指定命令，使用 '%~nx0 help' 查看帮助"
    exit /b 1
) else (
    call :print_error "未知命令: %command%"
    call :show_help
    exit /b 1
)

goto :eof

REM 脚本入口
call :main %*
endlocal